﻿using System;
using System.Collections.Generic;
using NBlog.Web.Application.Service.Entity;
using NBlog.Web.Application.Storage;

namespace NBlog.Web.Application.Service.Internal
{
    public interface ISearchService
    {
        void AddSearch(string queryText);
    }

    public class SearchService : ISearchService
    {
        private readonly IRepository _repository;

        public SearchService(IRepository repository)
        {
            _repository = repository;
        }

        public void AddSearch(string queryText)
        {
            if (string.IsNullOrWhiteSpace(queryText))
                throw new ArgumentNullException("queryText");

            var searchEntity = new SearchEntity();
            var isUpdate = _repository.Exists<SearchEntity>(queryText);
            var date = DateTime.Now.ToString("dd.MM.yyyy");

            if (isUpdate)
            {
                searchEntity = _repository.Single<SearchEntity>(queryText);
                searchEntity.Attempts += 1;
                searchEntity.Dates.Add(date);
            }
            else
            {
                searchEntity.Query = queryText;
                searchEntity.Attempts = 1;
                searchEntity.Dates = new List<string> { date };
            }

            _repository.Save(searchEntity);
        }
    }
}